// src/features/workspaces/api/use-update-workspace.ts
import {useCallback, useMemo, useState} from "react";
import {MARK_DATA_URL} from "@/lib/social/constants";
import {v4 as uuidv4} from 'uuid';
// import crypto from "crypto";

type Options = {
    onSuccess?: (workspaceId: string) => void
    onError?: (error: Error) => void
    onSettled?: () => void
    throwError?: boolean
}

type RequestType = {
    id: string
    name: string
} | null

type ResponseType = {
    id: string
} | null

// client
export const useUpdateWorkspace = () => {
    // create db workspace

    const [data, setData] = useState<RequestType>(null)
    const [error, setError] = useState<Error | null>(null)
    const [status, setStatus] =
        useState<"success" | "error" | "settled" | "pending" | null>()

    // const [isPending, setIsPending] = useState<boolean>(false)
    // const [isSuccess, setIsSuccess] = useState<boolean>(false)
    // const [isSettled, setIsSettled] = useState<boolean>(false)
    // const [isError, setIsError] = useState<boolean>(false)

    const isPending = useMemo(() => status === 'pending', [status])
    const isSuccess = useMemo(() => status === 'success', [status])
    const isSettled = useMemo(() => status === 'settled', [status])
    const isError = useMemo(() => status === 'error', [status])

    const mutate = useCallback(async (values: RequestType, options?: Options) => {
        try {
            setData(null)
            setError(null)
            setStatus('pending')

            // create workspace
            // const response = await fetch(`${MARK_DATA_URL}/workspaces/${values?.id}`, {
            const response = await fetch(`/api/workspaces/${values?.id}`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    name: values?.name
                })
            })
            const data = await response.json()

            setStatus('success')
            if (response.ok) options?.onSuccess?.(data.id)
            return values?.id
        } catch (error) {
            setStatus('error')
            options?.onError?.(error as Error)
            if (options?.throwError) throw error
        } finally {
            setStatus("settled")
            options?.onSettled?.()
        }
    }, []);

    return {
        mutate, error, isPending, isSuccess, isSettled,
    }
}